var mongoose = require('../../framework/mongoose');
var http = require('http');
var url = require('url');

var logger = require('../../framework/util').logger('app.service');
var App = require('./model').App;
var Subscription = require('../subscription/model').Subscription;
var Component = require('../component/model').Component;
var Template = require('../common/model').Template;

var CmsStore = require('../../public/ext/components/store/server/model').CmsStore;
var CmsGallery = require('../../public/ext/components/gallery/server/model').CmsGallery;
var CmsContactUs = require('../../public/ext/components/contactUs/server/model').CmsContactUs;

exports.createApp = function (name, descr, userId, callback) {
    Component.find().sort({'ordr': 1}).exec(function (err, objs) {
        if (!err) {
            var app = new App({
                name: name,
                descr: descr,
                theme: 'flat',
                skin: 'default',
                createTime: new Date(),
                updateTime: new Date(),
                user: userId
            });

            var defaultTemplateMap = {};
            Template.find({isDefault: true}).exec(function (err, templates) {
                for (var k = 0; k < templates.length; k++) {
                    eval('defaultTemplateMap.' + templates[k].component + '="' + templates[k].code + '"');
                }
                //logger.info(defaultTemplateMap);
                var subs = [];
                for (var i = 0; i < objs.length; i++) {
                    var template = eval('defaultTemplateMap.' + objs[i].code);
                    subs[i] = {code: objs[i].code,  name: objs[i].name, template: template,
                        title: objs[i].title, status: 1, order: i, createTime: new Date(), app: app._id};
                }
                Subscription.create(subs, function (err, m1,m2,m3,m4,m5,m6) { // create subs
                    app.subscriptions.push(m1,m2,m3,m4,m5,m6);

                    CmsStore.create({subscription: m1._id}, function (err, store) {
                    });
                    CmsGallery.create({subscription: m3._id}, function (err, gallery) {
                    });
                    CmsContactUs.create({subscription: m5._id, address: '苏州'}, function (err, contactUs) {
                    });
                    app.save(function(){
                        callback(app);
                        //logger.info('Init subs for app successfully!!!');
                    });
                });
            });
        }
    });
};